package org.port.contacts;

import java.util.ArrayList;
import java.util.List;

import org.port.util.Util;

import android.accounts.Account;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.RawContacts;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;

public class ContactsListLoader extends AsyncTaskLoader<List<ContactEntry>> {
	public final String TAG = "ContactsListLoader";
	public final String ACCOUNT_NAME = "account_name";
	public final String ACCOUNT_TYPE = "account_type";
	public final String ACCOUNT_TYPE_GOOGLE = "com.google";
	List<ContactEntry> mList;
	Context mContext;

	public ContactsListLoader(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		this.mContext = context;
	}

	private long[] getContactId() {
		Uri uri = RawContacts.CONTENT_URI;
		String[] projection = new String[] { RawContacts._ID,
				RawContacts.CONTACT_ID, RawContacts.DELETED };
		String selection = RawContacts.DELETED + " != 1";
		String[] selectionArgs = null;
		String sortOrder = null;
		Cursor c = mContext.getContentResolver().query(uri, projection,
				selection, selectionArgs, sortOrder);
		long[] res = null;
		try {
			if (c != null) {
				res = new long[c.getCount()];
				if (c.moveToFirst()) {
					while (c.moveToNext()) {
						res[c.getPosition()] = c.getLong(1);
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			c.close();
		}
		return res;
	}

	@Override
	public List<ContactEntry> loadInBackground() {
		Uri uri = Contacts.CONTENT_URI;
		String[] projection = new String[] { Contacts._ID,
				Contacts.DISPLAY_NAME, Contacts.LOOKUP_KEY, };
		String selection = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
				+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
				+ Contacts.DISPLAY_NAME + " != '' ))";
		String sortOrder = Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
		Cursor c = mContext.getContentResolver().query(uri, projection,
				selection, null, sortOrder);
		List<ContactEntry> entries = new ArrayList<ContactEntry>(c.getCount());
		if (c != null) {

			if (c.moveToFirst()) {
				String[] col = c.getColumnNames();
				Log.d("FLOW", col.length + "");
				for (int i = 0; i < col.length; i++) {
					Log.d("FLOW", col[i]);
				}
				Log.d("FLOW", "Loader cursor size is " + c.getCount());
				Log.d("FLOW", "Loader cursor size is " + c.getColumnCount());
				do {
					ContactEntry entry = new ContactEntry();
					entry.mId = c.getLong(0);
					entry.mName = c.getString(1);
					entry.mLookupKey = c.getString(2);
					entries.add(entry);
					Log.d("FLOW", entry.toString());
				} while (c.moveToNext());
			}
			if (!c.isClosed()) {
				c.close();
			}
		}
		return entries;
	}

	// @Override
	// public List<ContactEntry> loadInBackground() {
	// // TODO Auto-generated method stub
	// /*
	// * SQLiteDatabase database = SQLiteDatabase .openDatabase(
	// * "/data/data/com.android.providers.contacts/database/contacts2",
	// * null, SQLiteDatabase.OPEN_READONLY); Log.d(TAG,
	// * "database isOpen: " + database.isOpen()); Cursor rc =
	// * database.rawQuery("", null); List<ContactEntry> entries = new
	// * ArrayList<ContactsActivity.ContactEntry>(rc.getCount()); return
	// * entries;
	// */
	//
	// // 2012.04.26 changed contacts list load
	// Uri uri = Contacts.CONTENT_URI;
	// String[] projection = new String[] { Contacts._ID,
	// Contacts.DISPLAY_NAME, Contacts.LOOKUP_KEY, };
	// String selection = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
	// + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
	// + Contacts.DISPLAY_NAME + " != '' ))";
	// String sortOrder = Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
	// Cursor c = mContext.getContentResolver().query(uri, projection,
	// selection, null, sortOrder);
	// List<ContactEntry> entries = new ArrayList<ContactEntry>(
	// c.getCount());
	// if (c != null) {
	//
	// if (c.moveToFirst()) {
	// String[] col = c.getColumnNames();
	// Log.d("FLOW", col.length + "");
	// for (int i = 0; i < col.length; i++) {
	// Log.d("FLOW", col[i]);
	// }
	// Log.d("FLOW", "Loader cursor size is " + c.getCount());
	// Log.d("FLOW", "Loader cursor size is " + c.getColumnCount());
	// do {
	// ContactEntry entry = new ContactEntry();
	// entry.mId = c.getLong(0);
	// entry.mName = c.getString(1);
	// entry.mLookupKey = c.getString(2);
	// entries.add(entry);
	// Log.d("FLOW", entry.toString());
	// } while (c.moveToNext());
	// }
	// if (!c.isClosed()) {
	// c.close();
	// }
	// }
	// return entries;
	// }
	@Override
	public void deliverResult(List<ContactEntry> data) {
		// TODO Auto-generated method stub
		mList = data;
		if (isStarted()) {
			super.deliverResult(data);
		}
	}

	@Override
	protected void onStartLoading() {
		// TODO Auto-generated method stub
		if (mList != null) {
			deliverResult(mList);
		}
		if (takeContentChanged() || mList == null) {
			forceLoad();
		}
		// super.onStartLoading();
	}

	@Override
	public void forceLoad() {
		// TODO Auto-generated method stub
		String[] acc = getAccount();
		if ("".equals(acc[0])) {
			
		}
		super.forceLoad();
	}

	@Override
	protected void onStopLoading() {
		// TODO Auto-generated method stub
		cancelLoad();
		// super.onStopLoading();
	}

	@Override
	protected void onReset() {
		// TODO Auto-generated method stub
		super.onReset();
		onStopLoading();
		if (mList != null) {
			mList = null;
		}
	}

	public void setAccount(String accountName, String accountType) {
		Editor editor = Util.getPreferEditor(mContext);
		editor.putString(ACCOUNT_NAME, accountName);
		editor.putString(ACCOUNT_TYPE, accountType);
		editor.commit();
	}

	public String[] getAccount() {
		SharedPreferences preferences = Util.getPrefer(mContext);
		return new String[] { preferences.getString(ACCOUNT_NAME, ""),
				preferences.getString(ACCOUNT_TYPE, "") };
	}
}
